package com.rupeng.service;

import java.util.Date;
import java.util.List;

import com.rupeng.annotation.RupengCacheable;
import com.rupeng.annotation.RupengClearCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.rupeng.pojo.Card;
import com.rupeng.pojo.Setting;
import com.rupeng.pojo.User;
import com.rupeng.pojo.UserCard;
import com.rupeng.util.CommonUtils;

@Service
@RupengCacheable
public class UserCardService extends ManyToManyBaseService<UserCard, User, Card> {
	@Autowired
	private ClassesUserService classesUserService;
	@Autowired
	private SettingService settingService;
	@RupengClearCache
	public void activateFirstCard(Long classesId, Long cardId) {
		List<User> users = classesUserService.selectSecondListByFirstId(classesId);
		if (CommonUtils.isEmpty(users)) {
			return;
		}
		for (User user : users) {
			if (user.getIsTeacher()) {
				continue;
			}
			UserCard userCard = new UserCard();
			userCard.setCardId(cardId);
			userCard.setUserId(user.getId());
			if (super.isExisted(userCard)) {
				continue;
			}
			Setting setting = new Setting();
			setting.setName("card_valid_days");
			setting = settingService.selectOne(setting);
			int validDays = Integer.parseInt(setting.getValue());
			userCard.setCreateTime(new Date());
			Date endTime = new Date(userCard.getCreateTime().getTime()+validDays*1000L*60*60*24);
			userCard.setEndTime(endTime);
			super.insert(userCard);
		}
	}

}